//
//  YFPublishDongtaiView.m
//  project
//
//  Created by Winny Zhang on 2019/4/8.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFPublishDongtaiView.h"


#define IMAGES_VIEW_WIDTH (SCREEN_WIDTH - 24)
#define COL_COUNT (3)
#define IMAGE_MARGIN (14)

@interface YFPublishDongtaiView () <UITextViewDelegate, UIGestureRecognizerDelegate>


/**
 图片浏览数组数组
 */
@property (nonatomic, strong) NSArray <YBImageBrowseCellData *> *imageCellDatas;

/**
 视频浏览数据数组
 */
@property (nonatomic, strong) NSArray <YBVideoBrowseCellData *> *videoCellDatas;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;

/**
 contentView
 */
@property (weak, nonatomic) IBOutlet UIView *contentView;


/**
 textView的placeholder
 */
@property (weak, nonatomic) IBOutlet UILabel *placeholder;

/**
 承载图片我视频的View
 */
@property (weak, nonatomic) IBOutlet UIView *imagesView;

/**
 imagesView的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imagesViewConstraintHeight;

@property (weak, nonatomic) IBOutlet UIButton *locationBtn;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_x;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_y;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_width;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_height;

@property (weak, nonatomic) IBOutlet UIButton *addLocationBtn;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;

@end

@implementation YFPublishDongtaiView

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupShadowWithView:self.publishTextView];
    [self setupShadowWithView:self.imagesView];
    [self setupShadowWithView:self.contentView];
    [self.addBtn rounded:UIRectCornerAllCorners radius:5];
    [mNotificationCenter addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    [self startLocating];
    
    [self textRAC];
}

- (void)startLocating {
    @weakify(self)
    [HJLocationManager manager].locationBlock = ^(LocationModel * _Nonnull model) {
        @strongify(self)
        NSString *location = model.Thoroughfare;
        [self.locationBtn setTitle:location forState:(UIControlStateNormal)];
    };
}

- (void)setLocationStr:(NSString *)locationStr {
    self.locationLabel.text = locationStr;
}
-(void)textRAC {
    @weakify(self)
    [[self.publishTextView.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=200;
    }] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.publishTextView.text = [x substringToIndex:200];
    }];
    [[self.addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        if (self.photos.count==9) return;
        [self addImage];
    }];
    //我的位置
    [[self.locationBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self locationBtnClick];
    }];
}
- (void)locationBtnClick {
    self.locationAction();
}
#pragma mark - textViewDidChange 监听
- (void)textViewDidChange:(NSNotification *)not {
    if (self.publishTextView.text.length) {
        _placeholder.hidden = YES;
    }else{
        _placeholder.hidden = NO;
    }
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    NSString *lang = mode.primaryLanguage;
    static NSInteger length = 0;
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [self.publishTextView markedTextRange];
        if (!selectedRange) {
            length = self.publishTextView.text.length;
        }
    }else{
        length = self.publishTextView.text.length;
    }
    self.countLabel.text = [NSString stringWithFormat:@"%zd/200",length];
}

- (void)setPhotos:(NSArray<UIImage *> *)photos {
    _photos = photos;
    for (UIView *view in self.imagesView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    [self releasePublish];
    if (photos.count == 0) {
        self.addBtn_x.constant = 12;
        self.addBtn_y.constant = 12;
        return;
    }
    // 用于图片浏览的数据源数组
    NSMutableArray <YBImageBrowseCellData *> *imageCellDatas = [NSMutableArray arrayWithCapacity:9];
    CGFloat imageWidth = (IMAGES_VIEW_WIDTH - IMAGE_MARGIN * (COL_COUNT + 1)) / COL_COUNT;
    CGFloat imageHeight = imageWidth * 1.1;
    NSInteger totalCount = photos.count + 1;
    for (int i = 0; i < totalCount; i++) {
        // 图片所在的行
        NSInteger row = i / COL_COUNT;
        // 图片所在的列
        NSInteger col = i % COL_COUNT;
        CGFloat imageX = IMAGE_MARGIN + (IMAGE_MARGIN + imageWidth) * col;
        CGFloat imageY = IMAGE_MARGIN + (IMAGE_MARGIN + imageHeight) * row;
        // 添加图片按钮
        if (i == photos.count) {
            self.addBtn_x.constant = imageX;
            self.addBtn_y.constant = imageY;
            self.addBtn_width.constant = imageWidth;
            self.addBtn_height.constant = imageHeight;
            [self.addBtn rounded:UIRectCornerAllCorners radius:5];
            continue;
        }
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageWidth, imageHeight)];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;
        imageView.image = photos[i];
        [imageView rounded:(UIRectCornerAllCorners) radius:5];
        [self.imagesView addSubview:imageView];
        
        UIImageView * removeBtn = [UIImageView new];
        [removeBtn setImage:setImage(@"closeImage")];
        removeBtn.frame = CGRectMake(CGRectGetMaxX(imageView.frame)-removeBtn.image.size.width/2, removeBtn.image.size.height/2+imageY-10, removeBtn.image.size.width, removeBtn.image.size.height);
        removeBtn.tag = i;
        removeBtn.contentMode = UIViewContentModeScaleAspectFill;
        removeBtn.userInteractionEnabled = YES;
        [self.imagesView addSubview:removeBtn];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBrowserImages:)];
        [imageView addGestureRecognizer:tap];
        
        UITapGestureRecognizer *removeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImages:)];
        [removeBtn addGestureRecognizer:removeTap];
        
        // 创建数据源
        YBImageBrowseCellData *data = [YBImageBrowseCellData new];
        data.imageBlock = ^__kindof UIImage * _Nullable{
            return photos[i];
        };
        data.sourceObject = imageView;
        [imageCellDatas addObject:data];
    }
    
    self.imageCellDatas = imageCellDatas;
    
    // 一共有多少行
    NSInteger rows = ceil((double)totalCount / COL_COUNT);
    CGFloat imagesViewHeight = IMAGE_MARGIN * (rows + 1) + imageHeight * rows;
    self.imagesViewConstraintHeight.constant = imagesViewHeight;
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
    
    if (_updatePublishViewFrameAction) {
        CGFloat publishViewHeight = self.imagesViewConstraintHeight.constant + 220;
        CGFloat safeArea = IS_FULL_SCREEN ? 34 : 0;
        if (publishViewHeight < SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea) {
            publishViewHeight = SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea;
        }
        [UIView animateWithDuration:0.25 animations:^{
            [self layoutIfNeeded];
        }];
        _updatePublishViewFrameAction(publishViewHeight);
    }
}

- (void)setVideoCoverImage:(UIImage *)videoCoverImage {
    _videoCoverImage = videoCoverImage;
    // 清空子视图
    for (UIView *view in self.imagesView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    
    [self releasePublish];
    if (videoCoverImage == nil) {
        self.addBtn_x.constant = 14;
        self.addBtn_y.constant = 14;
        self.addBtn_width.constant = 150;
        self.addBtn_height.constant = 200;
        [self.addBtn rounded:UIRectCornerAllCorners radius:5];
        [UIView animateWithDuration:0.25 animations:^{
            [self layoutIfNeeded];
        }];
        return;
    }
    CGFloat imageX = 14;
    CGFloat imageY = 14;
    CGFloat imageWidth = 150;
    CGFloat imageHeight = 200;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageWidth, imageHeight)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.userInteractionEnabled = YES;
    [imageView rounded:(UIRectCornerAllCorners) radius:5];
    imageView.image = videoCoverImage;
    imageView.backgroundColor = [UIColor redColor];
    [self.imagesView addSubview:imageView];
    
    UIImageView * removeVideoBtn = [UIImageView new];
    [removeVideoBtn setImage:setImage(@"closeImage")];
    removeVideoBtn.frame = CGRectMake(CGRectGetMaxX(imageView.frame)-removeVideoBtn.image.size.width/2, removeVideoBtn.image.size.height/2+imageY-10, removeVideoBtn.image.size.width, removeVideoBtn.image.size.height);
    removeVideoBtn.contentMode = UIViewContentModeScaleAspectFill;
    removeVideoBtn.userInteractionEnabled = YES;
    [self.imagesView addSubview:removeVideoBtn];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    [removeVideoBtn addGestureRecognizer:tap];
    
    NSMutableArray <YBVideoBrowseCellData *> * videoCelldatas = [NSMutableArray arrayWithCapacity:1];
    
    YBVideoBrowseCellData *data = [YBVideoBrowseCellData new];
    data.url = _videoURL;
    data.sourceObject = imageView;
    [videoCelldatas addObject:data];
    self.videoCellDatas = videoCelldatas;
    
    UIButton *playButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
    playButton.frame = CGRectMake(0, 0, 70, 70);
    playButton.center = CGPointMake(75, 100);
    [imageView addSubview:playButton];
    
    @weakify(self)
    [[playButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self showBrowserVideo];
    }];
    
    self.imagesViewConstraintHeight.constant = 228;
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
    
    if (_updatePublishViewFrameAction) {
        CGFloat publishViewHeight = self.imagesViewConstraintHeight.constant + 220;
        CGFloat safeArea = IS_FULL_SCREEN ? 34 : 0;
        if (publishViewHeight < SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea) {
            publishViewHeight = SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea;
        }

        [UIView animateWithDuration:0.25 animations:^{
            [self layoutIfNeeded];
        }];
        _updatePublishViewFrameAction(publishViewHeight);
    }
}


#pragma mark - 按钮点击事件
- (void)addImage {
    [self showAlert];
}

- (void)showAlert {
    
    @weakify(self)
    [LEEAlert actionsheet].config
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        
        @strongify(self)
        action.title = @"拍摄";
        action.titleColor = [UIColor darkGrayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
        
        action.clickBlock = ^{
            YFCamera *camera = [YFCamera camera];
            [camera show];
            camera.maxSeconds = 15;
            camera.isTakePhoto = self.isImage;
            
            @weakify(self)
            [camera completedWithImage:^(UIImage * _Nullable image) {
                @strongify(self)
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.photos];
                [array addObject:image];
                self.photos = array;
            } withVideo:^(UIImage * _Nullable firstFrameImage, NSURL * _Nullable videoURL, long long duration) {
                @strongify(self)
                self.videoCoverImage = firstFrameImage;
                self->_videoURL = videoURL;
                self->_videoDuration = duration;
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"从手机相册选择";
        action.titleColor = [UIColor darkGrayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
        
        @strongify(self)
        action.clickBlock = ^{
            @weakify(self)
            [[TZImagePickerTool tools] selectVideoFor:self isDismiss:NO complete:^(UIImage *coverImage, NSString *filePath, long audioDurationSeconds) {
                @strongify(self)
                self->_videoURL = [NSURL URLWithString:filePath];
                self->_videoDuration = audioDurationSeconds;
                self.videoCoverImage = coverImage;
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.type = LEEActionTypeCancel;
        action.title = @"取消";
        action.titleColor = [UIColor grayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
    })
    .LeeShow();
}

#pragma mark - UIGestureRecognizerDelegate
- (void)showBrowserImages:(UIGestureRecognizer *)tap {
    YBImageBrowser *browser = [YBImageBrowser new];
    NSInteger currentIndex = tap.view.tag;
    browser.dataSourceArray = _imageCellDatas;
    [browser.defaultToolBar hideOperationButton];
    [browser.defaultSheetView setHidden:YES];
    browser.currentIndex = currentIndex;
    [browser show];
}
- (void)showBrowserVideo {
    YBImageBrowser *browser = [YBImageBrowser new];
    [browser.defaultToolBar hideOperationButton];
    [browser.defaultSheetView setHidden:YES];
    NSInteger currentIndex = 0;
    browser.dataSourceArray = _videoCellDatas;
    browser.currentIndex = currentIndex;
    [browser show];
}

-(void)releasePublish {
    // 是图片
    if (self.isImage) {
        if (_publishAction) {
            _publishAction(_publishTextView.text, NO, nil, nil, _photos);
        }
    }else {// 是视频
        if (_publishAction) {
            _publishAction(_publishTextView.text, YES, _videoURL, _videoCoverImage, nil);
        }
    }
}

#pragma 删除图片
-(void)removeImages:(UITapGestureRecognizer *)tap {
    NSMutableArray * photosArr = [NSMutableArray arrayWithArray:self.photos];
    [photosArr removeObjectAtIndex:tap.view.tag];
    self.photos = photosArr.mutableCopy;
    if (self.assets.count>0) {
        NSMutableArray * assetsArr = [NSMutableArray arrayWithArray:self.assets];
        [assetsArr removeObjectAtIndex:tap.view.tag];
        self.assets = assetsArr.mutableCopy;
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
}
#pragma 删除视频
-(void)tapGesture:(UITapGestureRecognizer *)tap {
    self.videoCoverImage = nil;
    _videoURL = @"";
}

@end
